// ignore_for_file: unused_import, avoid_print

import 'dart:async';
import 'dart:io';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_calls_uikit/tencent_calls_uikit.dart';
import 'package:tencent_chat_i18n_tool/tencent_chat_i18n_tool.dart';
import 'package:tencent_cloud_chat_demo/config.dart';
import 'package:tencent_cloud_chat_demo/generated/l10n.dart';
import 'package:tencent_cloud_chat_demo/src/pages/home_page.dart';
import 'package:tencent_cloud_chat_demo/src/pages/privacy/privacy_webview.dart';
import 'package:tencent_cloud_chat_demo/src/provider/theme.dart';
import 'package:tencent_cloud_chat_demo/src/routes.dart';
import 'package:tencent_cloud_chat_demo/utils/GenerateTestUserSig.dart';
import 'package:tencent_cloud_chat_demo/utils/commonUtils.dart';
import 'package:tencent_cloud_chat_demo/utils/request.dart';
import 'package:tencent_cloud_chat_demo/utils/toast.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/theme/color.dart';

class ForgetPage extends StatelessWidget {
  const ForgetPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<DefaultThemeData>(context).theme;
    return WillPopScope(
        onWillPop: () async {
          return true;
        },
        child: Scaffold(
          appBar: AppBar(
            iconTheme: const IconThemeData(
              color: Colors.white,
            ),
            shadowColor: theme.weakDividerColor,
            elevation: 1,
            title: Text(
              TIM_t("忘记密码"),
              style: const TextStyle(color: Colors.white, fontSize: 17),
            ),
            flexibleSpace: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(colors: [
                  theme.lightPrimaryColor ?? CommonColor.lightPrimaryColor,
                  theme.primaryColor ?? CommonColor.primaryColor
                ]),
              ),
            ),
          ),
          body: const AppLayout(),
          resizeToAvoidBottomInset: false,
        ));
  }
}

class AppLayout extends StatelessWidget {
  const AppLayout({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        SystemChannels.textInput.invokeMethod('TextInput.hide');
      },
      child: const Stack(
        children: [
          ForgetForm(),
        ],
      ),
    );
  }
}

class ForgetForm extends StatefulWidget {
  const ForgetForm({Key? key}) : super(key: key);

  @override
  _ForgetFormState createState() => _ForgetFormState();
}

class _ForgetFormState extends State<ForgetForm> {
  final CoreServicesImpl coreInstance = TIMUIKitCore.getInstance();

  String userID = '';
  String email = '';
  String emailCode = '';
  String password = '';
  String verify = '';
  String confirmPassword = '';
  bool isPasswordVisible = false;
  bool isVerify = false;
  String verifyText = '获取验证码';
  Timer? _timer;
  int _seconds = 60;
  final TextEditingController userIDController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController emailCodeController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController verifyController = TextEditingController();

  @override
  initState() {
    super.initState();
  }

  @override
  void dispose() {
    passwordController.dispose();
    userIDController.dispose();
    emailController.dispose();
    emailCodeController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  TextSpan webViewLink(String title, String url) {
    return TextSpan(
      text: TIM_t(title),
      style: const TextStyle(
        color: Color.fromRGBO(0, 110, 253, 1),
      ),
      recognizer: TapGestureRecognizer()
        ..onTap = () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => PrivacyDocument(title: title, url: url),
            ),
          );
        },
    );
  }

  directToLoginPage() {
    Routes().directToLoginPage();
  }

  /// 获取验证码
  Future<void> sendEmailCode() async {
    if (email.isEmpty) {
      ToastUtils.toast(TIM_t("请输入邮箱"));
      return;
    }

    if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(email)) {
      ToastUtils.toast(TIM_t("请输入有效的邮箱地址"));
      return;
    }

    if (isVerify) {
      return;
    }

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_seconds == 0) {
        _timer?.cancel();
        _seconds = 60;
        setState(() {
          isVerify = false;
          verifyText = '获取验证码';
        });
      } else {
        setState(() {
          _seconds--;
          isVerify = true;
          verifyText = '$_seconds s';
        });
      }
    });
  }

  updatePassword() async {
    if (userID.isEmpty) {
      ToastUtils.toast(TIM_t("请输入登录账号"));
      return;
    }

    if (email.isEmpty) {
      ToastUtils.toast(TIM_t("请输入邮箱"));
      return;
    }

    if (verify != '1234') {
      ToastUtils.toast(TIM_t('验证码错误'));
      return;
    }

    if (password.isEmpty) {
      ToastUtils.toast(TIM_t("请输入新密码"));
      return;
    }

    appRequest(
      method: 'post',
      path: 'https://yunpengim.daboluo.pro/api/user/resetpwdapp',
      data: {
        'userId': userID,
        'pwd': password,
      },
    ).then((res) async {
      if (res.data?['code'] == 1) {
        ToastUtils.toast(TIM_t('密码修改成功'));
        directToLoginPage();
      } else {
        ToastUtils.toast(TIM_t(res.data?['msg'] ?? '网络故障，请稍后重试'));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      context,
      designSize: const Size(750, 1624),
      minTextAdapt: true,
    );
    return Stack(
      children: [
        Positioned(
            child: Container(
          padding: const EdgeInsets.fromLTRB(40, 100, 40, 0),
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(30.0)),
          ),
          height:
              MediaQuery.of(context).size.height - CommonUtils.adaptHeight(600),
          width: MediaQuery.of(context).size.width,
          child: Form(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                TextField(
                  controller: userIDController,
                  autofocus: false,
                  decoration: InputDecoration(
                    contentPadding:
                        EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                    hintText: TIM_t("请输入登录账号"),
                    hintStyle: TextStyle(
                      fontSize: CommonUtils.adaptFontSize(24),
                      color: Colors.grey,
                    ),
                    prefixIcon: const Icon(Icons.person, color: Colors.grey),
                    suffixIcon: userID.isNotEmpty
                        ? IconButton(
                            icon: const Icon(Icons.clear, color: Colors.grey),
                            onPressed: () {
                              setState(() {
                                userID = '';
                                userIDController.clear();
                              });
                            },
                          )
                        : null,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.grey),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.black),
                    ),
                  ),
                  keyboardType: TextInputType.text,
                  onChanged: (v) {
                    setState(() {
                      userID = v;
                      debugPrint("userID: $userID");
                    });
                  },
                ),
                SizedBox(height: CommonUtils.adaptHeight(34)),
                TextField(
                  controller: emailController,
                  autofocus: false,
                  decoration: InputDecoration(
                    contentPadding:
                        EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                    hintText: TIM_t("请输入邮箱"),
                    hintStyle: TextStyle(
                      fontSize: CommonUtils.adaptFontSize(24),
                      color: Colors.grey,
                    ),
                    prefixIcon: const Icon(Icons.email, color: Colors.grey),
                    suffixIcon: email.isNotEmpty
                        ? IconButton(
                            icon: const Icon(Icons.clear, color: Colors.grey),
                            onPressed: () {
                              setState(() {
                                email = '';
                                emailController.clear();
                              });
                            },
                          )
                        : null,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.grey),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.black),
                    ),
                  ),
                  keyboardType: TextInputType.emailAddress,
                  onChanged: (v) {
                    setState(() {
                      email = v;
                    });
                  },
                ),
                SizedBox(height: CommonUtils.adaptHeight(34)),
                TextField(
                  controller: verifyController,
                  autofocus: false,
                  decoration: InputDecoration(
                    contentPadding:
                        EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                    hintText: TIM_t("请输入邮箱验证码"),
                    hintStyle: TextStyle(
                      fontSize: CommonUtils.adaptFontSize(24),
                      color: Colors.grey,
                    ),
                    prefixIcon: const Icon(Icons.lock, color: Colors.grey),
                    suffixIcon: TextButton(
                        onPressed: () {
                          sendEmailCode();
                        },
                        child: Text(
                          TIM_t(verifyText),
                          style: TextStyle(
                            fontSize: CommonUtils.adaptFontSize(24),
                            color: isVerify ? Colors.grey : Colors.black,
                          ),
                        )),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.grey),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.black),
                    ),
                  ),
                  keyboardType: TextInputType.text,
                  onChanged: (v) {
                    setState(() {
                      verify = v;
                    });
                  },
                ),
                SizedBox(height: CommonUtils.adaptHeight(34)),
                TextField(
                  controller: passwordController,
                  autofocus: false,
                  obscureText: !isPasswordVisible,
                  decoration: InputDecoration(
                    contentPadding:
                        EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                    hintText: TIM_t("请输入新密码"),
                    hintStyle: TextStyle(
                      fontSize: CommonUtils.adaptFontSize(24),
                      color: Colors.grey,
                    ),
                    prefixIcon: const Icon(Icons.lock, color: Colors.grey),
                    suffixIcon: IconButton(
                      icon: Icon(
                        isPasswordVisible
                            ? Icons.visibility
                            : Icons.visibility_off,
                        color: Colors.grey,
                      ),
                      onPressed: () {
                        setState(() {
                          isPasswordVisible = !isPasswordVisible;
                        });
                      },
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.grey),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.black),
                    ),
                  ),
                  keyboardType: TextInputType.text,
                  onChanged: (v) {
                    setState(() {
                      password = v;
                    });
                  },
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: CommonUtils.adaptHeight(200),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                            child: Text(
                              TIM_t("完成"),
                              style: const TextStyle(color: Colors.white),
                            ),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.black,
                            ),
                            onPressed: updatePassword),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ))
      ],
    );
  }
}
